package com.wangyadong.hobby.metric.gauge.lession2;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/12/1815:24
 * JMX Gauge
 * Cached Guage
 * Simple Gauge
 * Ratio Gauge
 * Derivative Gauge
 **/
public class SimleGaugeExample {

    private static MetricRegistry registry = new MetricRegistry();
    /***block queue**/
    private static final BlockingDeque queue = new LinkedBlockingDeque(1_000);


    private static ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();

    public static void main(String[] args) {
        registry.register(MetricRegistry.name(SimleGaugeExample.class, "queue-size"), new Gauge<Integer>() {
            @Override
            public Integer getValue() {
                return queue.size();
            }
        });
        reporter.start(10, TimeUnit.SECONDS);
        new Thread(() -> {

            while (true) {
                randomSleep();
                queue.add(System.nanoTime());
            }

        }).start();
        ///////////////////////////////////////////////////////////////////////////////////////
        new Thread(() -> {

            while (true) {
                randomSleep();
                queue.poll();
            }

        }).start();
    }


    private static void randomSleep() {
        try {
            TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(10));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
